/* open-fdes.c -- helper functions for discovering open ports on GNU/Hurd
   Copyright © 2021 Maxime Devos <maximedevos@gnu.org>

   This file is part of the GNU Shepherd.

   The GNU Shepherd is free software; you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3 of the License, or (at
   your option) any later version.

   The GNU Shepherd is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with the GNU Shepherd.  If not, see <http://www.gnu.org/licenses/>.  */

#define _GNU_SOURCE

#include <mach/lock-intern.h>
#include <hurd/fd.h>
#include <hurd/signal.h>

/* XXX __spin_lock and __mutex_lock are probably not
   supposed to be used outside glibc. */

/* Return the last file descriptor, or -1
   if there are no file descriptors. */
int
shepherd_last_fd (void)
{
  int i;
  HURD_CRITICAL_BEGIN;
  __mutex_lock (&_hurd_dtable_lock);
  i = _hurd_dtablesize - 1;
  for (; i >= 0; i--)
    {
      struct hurd_fd *d = _hurd_dtable[i];
      if (d == NULL)
	continue;
      _Bool null_p;
      __spin_lock (&d->port.lock);
      null_p = d->port.port == MACH_PORT_NULL;
      __spin_unlock (&d->port.lock);
      if (null_p)
	break;
      else
	continue;
    }
  __mutex_unlock (&_hurd_dtable_lock);
  HURD_CRITICAL_END;
  return i;
}
